package logic

import (
	"context"
	"errors"
	"video-hub/models/mysql"

	"video-hub/videorpc/internal/svc"
	"video-hub/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CollectAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCollectAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CollectAddLogic {
	return &CollectAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 视频收藏功能
func (l *CollectAddLogic) CollectAdd(in *videorpc.CollectAddRequest) (*videorpc.CollectAddResponse, error) {
	// todo: add your logic here and delete this line
	var findUser mysql.User
	err := findUser.FirstUserById(mysql.DB, in.UserId)
	if err != nil {
		return nil, errors.New("请先登录")
	}
	var video mysql.Video
	err = video.FirstVideoById(mysql.DB, in.VideoId)
	if err != nil {
		return nil, errors.New("该视频不存在")
	}
	var findCollect mysql.Collect
	err = findCollect.FindUserIdAndVideoId(mysql.DB, in.VideoId, in.UserId)
	if err != nil {
		return nil, err
	}
	if findCollect.ID != 0 {
		return nil, errors.New("已收藏该视频，无需重复操作")
	}
	collect := &mysql.Collect{
		VideoId: in.VideoId,
		UserId:  in.UserId,
	}
	err = collect.CollectAdd(mysql.DB)
	if err != nil {
		return nil, errors.New("收藏失败")
	}
	err = mysql.UpdateCollectNumAdd(mysql.DB, in.VideoId)
	if err != nil {
		return nil, errors.New("收藏+1失败")
	}

	return &videorpc.CollectAddResponse{
		CollectId: int64(collect.ID),
	}, nil
}
